<script setup>
import { reactive, ref, onMounted } from 'vue'
import api from "../api/index.js"
//import router from '../router/index.js';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router'
import sidentify from './sidentify.vue';
import { checkname, checkpass } from "../util/util.js";

const router = useRouter()
const formRef = ref({})
const loginObj = ref({})
const editObj = ref({})
const checked = ref(true)

let sidentifyMode = ref('') //输入框验证码
let identifyCode = ref('') //图形验证码
let identifyCodes = ref('1234567890abcdefjhijklmnopqrsduvwxyz') //验证码出现的数字和字母

//组件挂载
onMounted(() => {
    loginObj.value.username=localStorage.getItem("username");
    loginObj.value.password=localStorage.getItem("password");
    identifyCode.value = ''
    makeCode(identifyCodes.value, 4)
})

// 生成随机数
const randomNum = (min, max) => {
    max = max + 1
    return Math.floor(Math.random() * (max - min) + min)
}
// 随机生成验证码字符串
const makeCode = (o, l) => {
    for (let i = 0; i < l; i++) {
        identifyCode.value += o[randomNum(0, o.length)]
    }
}
// 更新验证码
const refreshCode = () => {
    identifyCode.value = ''
    makeCode(identifyCodes.value, 4)
}


const rules = reactive({
    username: [{ validator: checkname, trigger: "blur" }],
    password: [{ validator: checkpass, trigger: "blur" }],
})
const dologin = async function () {
    formRef.value.validate(async (valid) => {
        console.log(loginObj.value);
        if (valid) {

            //验证验证码不为空
            if (!sidentifyMode.value) {
                ElMessage({ type: 'error', message: '验证码不能为空！' })
                return
            }
            //验证验证码是否正确
            if (sidentifyMode.value != identifyCode.value) {
                ElMessage({ type: 'error', message: '验证码错误' })
                refreshCode()
                return
            } else {
                let result = await api.postform("/api/dologin", loginObj.value)
                console.log(result);
                if (result.code == 400) {
                    console.log("需要修改密码！！！！！！！！！！！！")
                    ElMessage({
                        type: 'warning',
                        message: '默认密码登录请先修改密码',
                    });
                    setTimeout(function () { router.push({ path: '/changepass' }); }, 500);

                } else {
                    if (result.code == 200 && result.data) {
                        //登录成功
                        if (checked.value) {
                            localStorage.setItem("username", loginObj.value.username);
                            localStorage.setItem("password", loginObj.value.password);
                        }
                        else {
                            localStorage.removeItem('username');
                            localStorage.removeItem('password');
                        }

                        //存放token
                        sessionStorage.setItem("tk", result.data);

                        //提示
                        ElMessage({
                            type: 'success',
                            message: '登陆成功',
                        });
                        //使用router进行导航
                        setTimeout(function () { router.push({ path: '/park' }); }, 500);

                    } else {
                        ElMessage({
                            type: 'error',
                            message: '账号或密码错误',
                        });
                    }

                }

            }
        } else {
            // ElMessage({
            //         type: 'error',
            //         message: '请输入正确格式的用户名或密码',
            //     });
            console.log("认证失败")
        }
    })
}
const goToChangePassword = function () {
    setTimeout(function () { router.push({ path: '/changepass' }); });
}
</script>

<template>
    <div class="container">
        <el-form :rules="rules" :model="loginObj" class="loginRoot" ref="formRef">
            <h3 class="loginTitle">系统登录</h3>
            <el-form-item prop="username">
                <el-input type="text" v-model="loginObj.username" auto-complete="off" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password" v-model="loginObj.password" auto-complete="off" placeholder="请输入密码"
                    show-password />
            </el-form-item>
            <el-form-item style="margin-bottom: 7px;">
                <!-- 新增的容器，使用flex布局 -->
                <div class="captcha-container">
                    <el-input placeholder="请输入验证码" v-model="sidentifyMode" ></el-input>
                    <div class="code" @click="refreshCode">
                        <sidentify :identifyCode="identifyCode"></sidentify>
                    </div>
                </div>
            </el-form-item>
            <el-checkbox v-model="checked" label="记住密码" name="type" style="margin-bottom: 10px;"></el-checkbox>
            <el-button type="primary" style="width: 100%" @click="dologin">登录</el-button>
            <el-button type="text" style="width: 95%; margin-top: 10px;" @click="goToChangePassword()">
                修改密码
            </el-button>
        </el-form>
    </div>
</template>



<style>
.captcha-container {
    display: flex;
    align-items: center;
    /* 垂直居中对齐 */
}

.code {
    margin-left: 10px;
    /* 调整输入框和验证码图片之间的间距 */
    cursor: pointer;
    /* 鼠标移到验证码图片上显示为手形 */
}

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    /* 让容器高度填满整个页面 */
}

.loginRoot {
    border-radius: 15px;
    background-clip: padding-box;
    margin: 50px auto;
    width: 350px;
    padding: 15px 35px;
    background: rgba(240, 248, 255, 0.5);
    /* Semi-transparent white */
    border: 1px solid #eaeaea;
    box-shadow: 0 0 25px #c6c6c6;
}

.loginTitle {
    margin: 15px auto 20px auto;
    text-align: center;
    color: #505050;
}
</style>